
# Copyright 2011 radialmind.org

import datetime
import settings
import logging
import os
import time
import wsgiref.handlers
import sys

import datamodel
import json
import settings

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp

class UpdateHandler(webapp.RequestHandler):
  
  """Handles user requests for updated lists of events.
  
  UpdateHandler only accepts "get" events, sent via web forms. It expects each
  request to include "min_latitude", "min_longitude", "max_latitude",
  "max_longitude" and "zoom" fields.
  """
  
  def get(self):
    lat = float(self.request.get('lat'))
    lon = float(self.request.get('lon'))
    zoom = self.request.get('zoom')

    serspots = []

    spots = datamodel.FlySpot.query( lat, lon, 100, 3 )

    for distance, spot in spots:
       serspot = datamodel.SerSpot()
       serspot.user = spot.user.nickname()
       serspot.spotname = spot.spotname
       serspot.lat = spot.location.lat
       serspot.lon = spot.location.lon
       serspot.experience = spot.experience
       serspot.rating = spot.rating
       serspot.videolink = spot.videolink
       serspots.append( serspot )

    output = {
      'spots': serspots
    }

    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write(json.encode(output));


class SaveHandler(webapp.RequestHandler):

  """Handles save events.
  """
  def post(self):
    
    # Get the current user and return if not logged in.
    user = users.get_current_user()
    if user == None:      
      return

    spotname  = self.request.get('spotname')
    lat = float(self.request.get('latitude'))
    lon = float(self.request.get('longitude'))
    experience = self.request.get('experience')

    new_spot = datamodel.FlySpot.add( user=user, spotname=spotname, lat=lat, lon=lon, experience=experience )
 
def main():
  
  """Main method called when the script is executed directly.
  
  This method is called each time the script is launched, and also has the
  effect of enabling caching for global variables.
  """
  
  application = webapp.WSGIApplication(
      [
        ('/spotevent/update', UpdateHandler),
        ('/spotevent/save', SaveHandler)
      ],
      debug = True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
